package com.yupi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.common.BaseResponse;
import com.yupi.common.ErrorCode;
import com.yupi.common.ResultUtils;
import com.yupi.constant.UserConstant;
import com.yupi.exception.BusinessException;
import com.yupi.model.domain.Userinfo;
import com.yupi.model.domain.request.UserLoginRequest;
import com.yupi.model.domain.request.UserRegisterRequest;
import com.yupi.service.UserinfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@RestController
@RequestMapping("/userInfo")
@Slf4j
public class UserInfoController {

    @Resource
    private UserinfoService userinfoService;

    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("/register")
    //用户注册接口
    public BaseResponse userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        long result = this.userinfoService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    //用户登陆接口
    public BaseResponse doLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Userinfo userinfo = this.userinfoService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(userinfo);
    }

    @PostMapping("/logout")
    //用户注销接口
    public BaseResponse logout(HttpServletRequest request) {

        if (request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        int result = userinfoService.userLogout(request);
        return ResultUtils.success(result);

    }

    @GetMapping("/searchByTags")
    public BaseResponse searchUserByTags(@RequestParam(required = false) List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签为空");
        }
        List<Userinfo> userinfos = this.userinfoService.searchUserByTags(tagNameList);
        return ResultUtils.success(userinfos);
    }

    //根据用户名称查询用户
    @GetMapping("/search")
    public BaseResponse searchUser(String username, HttpServletRequest request) {
        //鉴权  仅管理员可以操作
        if (!this.userinfoService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        QueryWrapper<Userinfo> qw = new QueryWrapper<>();
        if (!StringUtils.isBlank(username)) {
            //如果参数为空，默认就是模糊查询
            qw.like("username", username);
        }
        List<Userinfo> userinfos = this.userinfoService.list(qw);
        //数据脱敏后返回
        List<Userinfo> userinfoList = userinfos.stream().map(userinfo -> userinfoService.getSafetyUser(userinfo)).collect(Collectors.toList());

        return ResultUtils.success(userinfoList);
    }

    //用户获取数据
    @GetMapping("/recommend")
    public BaseResponse recommendUsers(long pageNum, long pageSize, HttpServletRequest request) {
        Page<Userinfo> uesrPage =  this.userinfoService.recommendUsers(pageNum, pageSize, request);
        return ResultUtils.success(uesrPage);
    }


    //删除用户
    @DeleteMapping("/delete")
    public BaseResponse deleteUser(Long id, HttpServletRequest request) {
        //鉴权  仅管理员可以操作
        if (!this.userinfoService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id不能小于0");
        }
        //由于修改了mp的逻辑删除配置，调用删除方法会自动转为update方法逻辑删除
        boolean result = this.userinfoService.removeById(id);
        return ResultUtils.success(result);
    }

    @PutMapping("/updateUser")
    public BaseResponse updateUser(@RequestBody Userinfo userinfo, HttpServletRequest request) {
        if (userinfo == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Userinfo loginUser = this.userinfoService.getLoginUser(request);
        Integer result = this.userinfoService.updateUser(userinfo, loginUser);
        return ResultUtils.success(result);
    }


    //获取当前登录用户接口
    @GetMapping("/currentUser")
    public BaseResponse<Userinfo> getCurrentUser(HttpServletRequest request) {
        //取出登录用户信息
        Userinfo userinfo = (Userinfo) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATUS);

        if (userinfo == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        Long id = userinfo.getId();
        Userinfo user = userinfoService.getById(id);
        //TODO 校验用户是否合法(状态)
        return ResultUtils.success(userinfoService.getSafetyUser(user));
    }


}
